// 获取用户详情
async function getUserDetailsRequest(data) {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/getUserDetails.php',
        type: 'get',
        data: data
    })
    return res
}

// 渲染用户详情
async function renderUserDetails() {
    const user_id = JSON.parse(localStorage.getItem('userInfo')).id
    const userData = await getUserDetailsRequest({
        user_id
    })
    if (userData.code === 1) {
        document.querySelector('.main .main-content .form .username input').value = userData.data.username
        document.querySelector('.main .main-content .form .email input').value = userData.data.email
    }
}
renderUserDetails()

// 修改用户信息请求
async function editUserInfo(data) {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/userEdit.php',
        type: 'post',
        data: data
    })
    return res
}

// 修改按钮点击事件
$('.content-main .form .btn').click(async function () {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const user_id = JSON.parse(localStorage.getItem('userInfo')).id
    const username = document.querySelector('.content-main .form .username input').value
    const email = document.querySelector('.content-main .form .email input').value

    if (!username) {
        myAlert(false, '用户名不能为空')
        return false
    }

    if (!email) {
        myAlert(false, '邮箱不能为空')
        return false
    }

    if (username.length < 2) {
        myAlert(false, '用户名长度不能小于2位')
    }

    const res = await editUserInfo({
        user_id,
        username,
        email
    })

    if (res.code === 1) {
        location.reload()
    } else {
        myAlert(false, res.msg)
    }
})